from fastapi import APIRouter, File, UploadFile
from fastapi.responses import JSONResponse
import os

library_router = APIRouter()


@library_router.post("/api/uploadPdf")
async def upload_pdf(file: UploadFile = File(...)):
    data_directory = "./data/pdf/"
    if not os.path.exists(data_directory):
        os.makedirs(data_directory)
    try:
        filename = file.filename

        if not filename.endswith(".pdf"):
            return JSONResponse(status_code=400, content={"message": "Only PDF files are allowed"})

        save_path = os.path.join(data_directory, filename)
        with open(save_path, "wb") as f:
            contents = file.read()
            f.write(contents)

        return JSONResponse(status_code=200, content={"message": "File uploaded successfully", "filename": filename})

    except Exception as e:
        return JSONResponse(status_code=500, content={"message": str(e)})
